package ee.maoinvest.frontend.controller.command.statisticsquerycommands;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import ee.maoinvest.backend.model.data.RegularReading;
import ee.maoinvest.backend.services.RegularReadingsService;
import ee.maoinvest.backend.services.implementations.RegularReadingsServiceImpl;
import ee.maoinvest.frontend.controller.command.Command;
import ee.maoinvest.frontend.controller.formstringdataconverters.statisticsqueryforms.GetAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsFormConverter;

public class FillGetAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsWithInitialDataCommand 
	implements Command
{
	private Logger logger = Logger.getLogger(
			FillGetAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsWithInitialDataCommand.class);
	private int operationResult = 0;
	private final int OPERATION_SUCCESSFUL = 1;
	private final int PROBABLY_A_DATABASE_ERROR = -1;
	
	@Override
	public int executeCommand(HttpServletRequest request,
			HttpServletResponse response) 
	{
		GetAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsFormConverter 
			getAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsFormConverter = null;
		RegularReading latestRegularReading = null;
		
		try 
		{
			RegularReadingsService regularReadingsService = new RegularReadingsServiceImpl();
			latestRegularReading = regularReadingsService.getLatestRegularReading();
			getAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsFormConverter = 
					new GetAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsFormConverter();
			
			getAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsFormConverter.setInitialDataIntoConverter(
					latestRegularReading);
			request.setAttribute("getAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsFormConverter", 
					getAllEnterprisesStatisticsThatAreHavingContractWithSubstationMainElectricityMeterBetweenGivenRegularReadingsFormConverter);
			
			HttpSession session = request.getSession();
			session.setAttribute("latestRegularReading", latestRegularReading);
			operationResult = OPERATION_SUCCESSFUL;
			
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			logger.error(e.getMessage());
			return PROBABLY_A_DATABASE_ERROR;
		}
		
		return operationResult;
	}
}

